"""
潜力预测师智能体 - 专业的人才潜力评估和预测
具备学习轨迹分析、成长潜力评估、职业发展预测等能力
"""

import asyncio
from typing import List, Dict, Any, Optional
from datetime import datetime
import json

from ...core.interfaces import Task, TaskStatus
from ..base_agent import BaseAgent


class PotentialForecaster(BaseAgent):
    """潜力预测师智能体"""
    
    def __init__(self):
        super().__init__(
            name="potential_forecaster",
            capabilities=[
                "potential_assessment",
                "growth_prediction",
                "learning_trajectory_analysis",
                "skill_gap_analysis",
                "career_path_forecasting",
                "adaptability_evaluation"
            ]
        )
        
        # 评估维度权重
        self.assessment_weights = {
            "learning_ability": 0.25,
            "adaptability": 0.20,
            "growth_trajectory": 0.20,
            "skill_development": 0.15,
            "leadership_potential": 0.10,
            "innovation_capacity": 0.10
        }
    
    async def _initialize_agent_specific(self):
        """初始化潜力预测特定功能"""
        pass
    
    async def _process_task_internal(self, task: Task) -> Dict[str, Any]:
        """处理潜力预测任务"""
        try:
            task_type = task.task_type
            
            if task_type == "assess_potential":
                return await self._assess_comprehensive_potential(task)
            elif task_type == "analyze_learning_trajectory":
                return await self._analyze_learning_trajectory(task)
            elif task_type == "predict_growth":
                return await self._predict_growth_potential(task)
            elif task_type == "evaluate_adaptability":
                return await self._evaluate_adaptability(task)
            else:
                return await self._assess_comprehensive_potential(task)
                
        except Exception as e:
            return {"error": str(e), "agent": self.name}
    
    async def _assess_comprehensive_potential(self, task: Task) -> Dict[str, Any]:
        """综合潜力评估"""
        try:
            # 使用RAG查询获取候选人信息
            rag_result = await self.query_rag(
                query=f"人才潜力评估：{task.description}",
                template_name="general_qa",
                top_k=8
            )
            
            # 多维度潜力分析
            potential_analysis = await asyncio.gather(
                self._analyze_learning_ability(rag_result),
                self._analyze_adaptability_indicators(rag_result),
                self._analyze_growth_trajectory(rag_result),
                self._analyze_skill_development_pattern(rag_result),
                self._analyze_leadership_indicators(rag_result),
                self._analyze_innovation_capacity(rag_result)
            )
            
            # 整合分析结果
            integrated_assessment = await self._integrate_potential_assessment(potential_analysis)
            
            # 计算综合潜力分数
            potential_score = await self._calculate_potential_score(integrated_assessment)
            
            # 生成发展建议
            development_recommendations = await self._generate_development_recommendations(integrated_assessment)
            
            return {
                "assessment_type": "comprehensive_potential",
                "query": task.description,
                "potential_analysis": integrated_assessment,
                "potential_score": potential_score,
                "development_recommendations": development_recommendations,
                "future_trajectory": await self._predict_future_trajectory(integrated_assessment),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "assessment_type": "comprehensive_potential"}
    
    async def _analyze_learning_trajectory(self, task: Task) -> Dict[str, Any]:
        """分析学习轨迹"""
        try:
            learning_query = f"学习轨迹分析：{task.description}"
            
            rag_result = await self.query_rag(query=learning_query, top_k=6)
            
            # 学习模式分析
            learning_patterns = {
                "formal_learning": await self._identify_formal_learning(rag_result),
                "informal_learning": await self._identify_informal_learning(rag_result),
                "skill_acquisition_speed": await self._assess_skill_acquisition_speed(rag_result),
                "learning_consistency": await self._assess_learning_consistency(rag_result)
            }
            
            # 学习能力评分
            learning_scores = await self._score_learning_ability(learning_patterns)
            
            return {
                "assessment_type": "learning_trajectory",
                "query": learning_query,
                "learning_patterns": learning_patterns,
                "learning_scores": learning_scores,
                "learning_insights": await self._generate_learning_insights(learning_patterns),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "assessment_type": "learning_trajectory"}
    
    async def _predict_growth_potential(self, task: Task) -> Dict[str, Any]:
        """预测成长潜力"""
        try:
            growth_query = f"成长潜力预测：{task.description}"
            
            rag_result = await self.query_rag(query=growth_query, top_k=8)
            
            # 成长指标分析
            growth_indicators = {
                "career_progression_rate": await self._analyze_career_progression(rag_result),
                "responsibility_growth": await self._analyze_responsibility_growth(rag_result),
                "skill_expansion": await self._analyze_skill_expansion(rag_result),
                "impact_escalation": await self._analyze_impact_escalation(rag_result)
            }
            
            # 未来成长预测
            growth_prediction = await self._model_future_growth(growth_indicators)
            
            return {
                "assessment_type": "growth_prediction",
                "query": growth_query,
                "growth_indicators": growth_indicators,
                "growth_prediction": growth_prediction,
                "growth_timeline": await self._create_growth_timeline(growth_prediction),
                "risk_factors": await self._identify_growth_risks(growth_indicators),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "assessment_type": "growth_prediction"}
    
    async def _evaluate_adaptability(self, task: Task) -> Dict[str, Any]:
        """评估适应性"""
        try:
            adaptability_query = f"适应性评估：{task.description}"
            
            rag_result = await self.query_rag(query=adaptability_query, top_k=6)
            
            # 适应性指标
            adaptability_metrics = {
                "technology_adaptation": await self._assess_tech_adaptation(rag_result),
                "role_flexibility": await self._assess_role_flexibility(rag_result),
                "industry_adaptability": await self._assess_industry_adaptability(rag_result),
                "change_resilience": await self._assess_change_resilience(rag_result)
            }
            
            # 适应性评分
            adaptability_score = await self._calculate_adaptability_score(adaptability_metrics)
            
            return {
                "assessment_type": "adaptability_evaluation",
                "query": adaptability_query,
                "adaptability_metrics": adaptability_metrics,
                "adaptability_score": adaptability_score,
                "adaptation_strategies": await self._recommend_adaptation_strategies(adaptability_metrics),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "assessment_type": "adaptability_evaluation"}
    
    # 潜力分析核心方法
    async def _analyze_learning_ability(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析学习能力"""
        answer = rag_result.get("answer", "")
        
        learning_indicators = {
            "continuous_learning": self._detect_continuous_learning(answer),
            "skill_diversification": self._detect_skill_diversification(answer),
            "certification_pursuit": self._detect_certifications(answer),
            "knowledge_application": self._detect_knowledge_application(answer)
        }
        
        learning_score = sum(1 for indicator in learning_indicators.values() if indicator) / len(learning_indicators)
        
        return {
            "indicators": learning_indicators,
            "score": learning_score,
            "assessment": "strong" if learning_score > 0.7 else "moderate" if learning_score > 0.4 else "needs_improvement"
        }
    
    async def _analyze_adaptability_indicators(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析适应性指标"""
        answer = rag_result.get("answer", "")
        
        adaptability_signals = {
            "role_transitions": self._count_role_transitions(answer),
            "technology_adoption": self._detect_tech_adoption(answer),
            "industry_changes": self._detect_industry_changes(answer),
            "problem_solving": self._detect_problem_solving(answer)
        }
        
        adaptability_score = min(sum(adaptability_signals.values()) / 10, 1.0)
        
        return {
            "signals": adaptability_signals,
            "score": adaptability_score,
            "assessment": "highly_adaptable" if adaptability_score > 0.8 else "adaptable" if adaptability_score > 0.5 else "traditional"
        }
    
    async def _analyze_growth_trajectory(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析成长轨迹"""
        answer = rag_result.get("answer", "")
        
        growth_metrics = {
            "position_advancement": self._detect_position_advancement(answer),
            "responsibility_increase": self._detect_responsibility_increase(answer),
            "impact_growth": self._detect_impact_growth(answer),
            "recognition_patterns": self._detect_recognition_patterns(answer)
        }
        
        growth_trend = "ascending" if sum(growth_metrics.values()) > 2 else "stable" if sum(growth_metrics.values()) > 1 else "unclear"
        
        return {
            "metrics": growth_metrics,
            "trend": growth_trend,
            "velocity": self._calculate_growth_velocity(growth_metrics)
        }
    
    async def _analyze_skill_development_pattern(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析技能发展模式"""
        answer = rag_result.get("answer", "")
        
        skill_patterns = {
            "breadth_expansion": self._assess_skill_breadth(answer),
            "depth_development": self._assess_skill_depth(answer),
            "emerging_skills": self._detect_emerging_skills(answer),
            "skill_integration": self._assess_skill_integration(answer)
        }
        
        return {
            "patterns": skill_patterns,
            "development_style": self._classify_development_style(skill_patterns),
            "future_potential": self._predict_skill_potential(skill_patterns)
        }
    
    async def _analyze_leadership_indicators(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析领导力指标"""
        answer = rag_result.get("answer", "")
        
        leadership_signals = {
            "team_management": "管理" in answer or "团队" in answer,
            "project_leadership": "项目" in answer and "负责" in answer,
            "mentoring_others": "指导" in answer or "培训" in answer,
            "strategic_thinking": "战略" in answer or "规划" in answer
        }
        
        leadership_score = sum(1 for signal in leadership_signals.values() if signal) / len(leadership_signals)
        
        return {
            "signals": leadership_signals,
            "score": leadership_score,
            "potential": "high" if leadership_score > 0.6 else "moderate" if leadership_score > 0.3 else "developing"
        }
    
    async def _analyze_innovation_capacity(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析创新能力"""
        answer = rag_result.get("answer", "")
        
        innovation_indicators = {
            "creative_problem_solving": "创新" in answer or "优化" in answer,
            "new_approach_adoption": "新方法" in answer or "改进" in answer,
            "technology_pioneering": "新技术" in answer or "前沿" in answer,
            "process_improvement": "流程" in answer and "改进" in answer
        }
        
        innovation_score = sum(1 for indicator in innovation_indicators.values() if indicator) / len(innovation_indicators)
        
        return {
            "indicators": innovation_indicators,
            "score": innovation_score,
            "capacity": "innovative" if innovation_score > 0.5 else "adaptive" if innovation_score > 0.25 else "traditional"
        }
    
    # 辅助检测方法
    def _detect_continuous_learning(self, text: str) -> bool:
        """检测持续学习"""
        learning_keywords = ["学习", "培训", "课程", "证书", "进修"]
        return any(keyword in text for keyword in learning_keywords)
    
    def _detect_skill_diversification(self, text: str) -> bool:
        """检测技能多样化"""
        skill_count = len([skill for skill in ["Python", "Java", "管理", "分析", "设计"] if skill in text])
        return skill_count >= 3
    
    def _detect_certifications(self, text: str) -> bool:
        """检测认证证书"""
        cert_keywords = ["认证", "证书", "资格", "考试"]
        return any(keyword in text for keyword in cert_keywords)
    
    def _detect_knowledge_application(self, text: str) -> bool:
        """检测知识应用"""
        application_keywords = ["应用", "实践", "项目", "解决"]
        return any(keyword in text for keyword in application_keywords)
    
    def _count_role_transitions(self, text: str) -> int:
        """统计角色转换次数"""
        transition_keywords = ["转岗", "调岗", "升职", "晋升"]
        return sum(text.count(keyword) for keyword in transition_keywords)
    
    def _detect_tech_adoption(self, text: str) -> bool:
        """检测技术采用"""
        tech_keywords = ["新技术", "学习", "掌握", "使用"]
        return sum(text.count(keyword) for keyword in tech_keywords) >= 2
    
    def _detect_industry_changes(self, text: str) -> bool:
        """检测行业变化"""
        return "行业" in text and ("转换" in text or "变化" in text)
    
    def _detect_problem_solving(self, text: str) -> bool:
        """检测问题解决"""
        solving_keywords = ["解决", "问题", "挑战", "克服"]
        return sum(text.count(keyword) for keyword in solving_keywords) >= 2
    
    def _detect_position_advancement(self, text: str) -> bool:
        """检测职位提升"""
        advancement_keywords = ["晋升", "提升", "升职", "高级"]
        return any(keyword in text for keyword in advancement_keywords)
    
    def _detect_responsibility_increase(self, text: str) -> bool:
        """检测责任增加"""
        responsibility_keywords = ["负责", "管理", "领导", "主导"]
        return sum(text.count(keyword) for keyword in responsibility_keywords) >= 2
    
    def _detect_impact_growth(self, text: str) -> bool:
        """检测影响力增长"""
        impact_keywords = ["影响", "贡献", "成果", "业绩"]
        return any(keyword in text for keyword in impact_keywords)
    
    def _detect_recognition_patterns(self, text: str) -> bool:
        """检测认可模式"""
        recognition_keywords = ["奖励", "表彰", "认可", "优秀"]
        return any(keyword in text for keyword in recognition_keywords)
    
    def _assess_skill_breadth(self, text: str) -> float:
        """评估技能广度"""
        diverse_skills = ["技术", "管理", "沟通", "分析", "创新"]
        skill_count = sum(1 for skill in diverse_skills if skill in text)
        return skill_count / len(diverse_skills)
    
    def _assess_skill_depth(self, text: str) -> float:
        """评估技能深度"""
        depth_indicators = ["专家", "精通", "资深", "深入"]
        return sum(1 for indicator in depth_indicators if indicator in text) / len(depth_indicators)
    
    def _detect_emerging_skills(self, text: str) -> bool:
        """检测新兴技能"""
        emerging_keywords = ["新兴", "前沿", "最新", "创新"]
        return any(keyword in text for keyword in emerging_keywords)
    
    def _assess_skill_integration(self, text: str) -> bool:
        """评估技能整合"""
        integration_keywords = ["结合", "整合", "融合", "综合"]
        return any(keyword in text for keyword in integration_keywords)
    
    # 计算和预测方法
    def _calculate_growth_velocity(self, growth_metrics: Dict[str, bool]) -> float:
        """计算成长速度"""
        return sum(1 for metric in growth_metrics.values() if metric) / len(growth_metrics)
    
    def _classify_development_style(self, skill_patterns: Dict[str, Any]) -> str:
        """分类发展风格"""
        breadth = skill_patterns.get("breadth_expansion", 0)
        depth = skill_patterns.get("depth_development", 0)
        
        if breadth > 0.7 and depth > 0.7:
            return "T-shaped"
        elif breadth > depth:
            return "broad_generalist"
        elif depth > breadth:
            return "deep_specialist"
        else:
            return "balanced"
    
    def _predict_skill_potential(self, skill_patterns: Dict[str, Any]) -> str:
        """预测技能潜力"""
        emerging = skill_patterns.get("emerging_skills", False)
        integration = skill_patterns.get("skill_integration", False)
        
        if emerging and integration:
            return "high_potential"
        elif emerging or integration:
            return "moderate_potential"
        else:
            return "steady_growth"
    
    # 整合和评分方法
    async def _integrate_potential_assessment(self, potential_analysis: List[Dict[str, Any]]) -> Dict[str, Any]:
        """整合潜力评估"""
        return {
            "learning_ability": potential_analysis[0],
            "adaptability": potential_analysis[1],
            "growth_trajectory": potential_analysis[2],
            "skill_development": potential_analysis[3],
            "leadership_potential": potential_analysis[4],
            "innovation_capacity": potential_analysis[5]
        }
    
    async def _calculate_potential_score(self, integrated_assessment: Dict[str, Any]) -> Dict[str, float]:
        """计算潜力分数"""
        scores = {}
        
        for dimension, weight in self.assessment_weights.items():
            dimension_data = integrated_assessment.get(dimension, {})
            dimension_score = dimension_data.get("score", 0.5)
            scores[dimension] = dimension_score * 100
        
        # 计算加权总分
        weighted_total = sum(
            scores[dim] * weight 
            for dim, weight in self.assessment_weights.items()
        )
        
        scores["overall_potential"] = weighted_total
        
        return scores
    
    async def _generate_development_recommendations(self, integrated_assessment: Dict[str, Any]) -> List[str]:
        """生成发展建议"""
        recommendations = []
        
        # 基于各维度评估生成建议
        learning_ability = integrated_assessment.get("learning_ability", {})
        if learning_ability.get("score", 0) < 0.6:
            recommendations.append("建议加强持续学习，关注行业新趋势")
        
        adaptability = integrated_assessment.get("adaptability", {})
        if adaptability.get("score", 0) < 0.6:
            recommendations.append("建议提升适应性，多尝试跨领域挑战")
        
        leadership_potential = integrated_assessment.get("leadership_potential", {})
        if leadership_potential.get("score", 0) > 0.7:
            recommendations.append("具备良好领导潜质，建议寻求管理机会")
        
        if not recommendations:
            recommendations.append("整体潜力表现良好，建议继续保持发展势头")
        
        return recommendations
    
    async def _predict_future_trajectory(self, integrated_assessment: Dict[str, Any]) -> Dict[str, Any]:
        """预测未来轨迹"""
        growth_trajectory = integrated_assessment.get("growth_trajectory", {})
        adaptability = integrated_assessment.get("adaptability", {})
        
        trajectory_prediction = {
            "short_term": "稳步发展",
            "medium_term": "有望获得晋升机会",
            "long_term": "具备高级管理潜力",
            "key_factors": [
                "持续学习能力",
                "适应变化能力",
                "领导潜质发展"
            ]
        }
        
        # 基于评估调整预测
        if growth_trajectory.get("trend") == "ascending":
            trajectory_prediction["confidence"] = "high"
        else:
            trajectory_prediction["confidence"] = "moderate"
        
        return trajectory_prediction
    
    # 学习轨迹相关方法（简化实现）
    async def _identify_formal_learning(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """识别正式学习"""
        return {"type": "formal", "instances": 2, "recent": True}
    
    async def _identify_informal_learning(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """识别非正式学习"""
        return {"type": "informal", "instances": 5, "continuous": True}
    
    async def _assess_skill_acquisition_speed(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """评估技能获取速度"""
        return {"speed": "fast", "score": 0.8}
    
    async def _assess_learning_consistency(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """评估学习一致性"""
        return {"consistency": "high", "score": 0.9}
    
    async def _score_learning_ability(self, learning_patterns: Dict[str, Any]) -> Dict[str, float]:
        """为学习能力评分"""
        return {
            "formal_learning_score": 0.8,
            "informal_learning_score": 0.9,
            "acquisition_speed_score": 0.8,
            "consistency_score": 0.9,
            "overall_learning_score": 0.85
        }
    
    async def _generate_learning_insights(self, learning_patterns: Dict[str, Any]) -> List[str]:
        """生成学习洞察"""
        return [
            "候选人具有良好的学习习惯",
            "技能获取速度较快",
            "学习方式多样化"
        ]